<?php

namespace Muyuxuanpay\cms;

use Muyuxuanpay\cms\library\EasySms;
use Muyuxuanpay\tool\Mtool;

class MuCms
{
    protected $config;
    protected $message;
    public function __construct(array $config=[])
    {
        $this->setConfig($config);
    }
    public function getConfig()
    {
        return $this->config;
    }
    public function getMessage()
    {
        return $this->message;
    }
    public function setConfig(array $config=[])
    {
        $baseConfig = include __DIR__.'/config/smsconfig.php';
        if(empty($config)){
            if(empty($this->config)){
                $config = $baseConfig;
            }else{
                $config = $this->config;
            }
        }else{
            $config = Mtool::depth_array_merge($baseConfig,$config);
        }
        $this->config = $config;
    }
    protected static function setStaticConfig(array $config=[])
    {
        $baseConfig = include __DIR__.'/config/smsconfig.php';
        if(empty($config)){
            $config = $baseConfig;
        }else{
            $config = Mtool::depth_array_merge($baseConfig,$config);
        }
        return $config;
    }

    /**
     * @param $phone
     * @param array $data [
     * 'content'  => '您的验证码为: 12354878',
     * 'template' =>"模版id",
     * 'data' => [
     * 'code' => 12354878
     * ],
     * ]
     * @param array $config 配置
     * @return bool
     */
    public function sendCms($phone,array $data,$config=[]){
        if(!empty($config)){
            $this->setConfig($config);
        }
        $easySms = new EasySms($this->config);
        try {
            $result = $easySms->send($phone, $data);
        }catch (\Exception $exception){
            $this->message = $exception->getExceptions();
            return false;
        }
        $is_suc = false;
        foreach ($result as $v){
            if($v['status']=='success'){
                $is_suc = true;
                break;
            }
        }
        return $is_suc;
    }

    /**
     * @param $phone
     * @param array $data [
     * 'content'  => '您的验证码为: 12354878',
     * 'template' =>"模版id",
     * 'data' => [
     * 'code' => 12354878
     * ],
     * ]
     * @param $config
     * @return bool
     */
    public static function sendStaticCms($phone,array $data,$config=[])
    {
        if(!empty($config)){
            $config = self::setStaticConfig($config);
        }
        $easySms = new EasySms($config);
        try {
            $result = $easySms->send($phone, $data);
        }catch (\Exception $exception){
            return false;
        }
        $is_suc = false;
        foreach ($result as $v){
            if($v['status']=='success'){
                $is_suc = true;
                break;
            }
        }
        return $is_suc;
    }
}